package org.jeecg.modules.controller;

import java.util.Arrays;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;
import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.net.URLDecoder;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.catalina.security.SecurityUtil;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.subject.Subject;
import org.jeecg.common.api.vo.Result;
import org.jeecg.common.constant.FilePathConstant;
import org.jeecg.common.system.query.QueryGenerator;
import org.jeecg.common.system.vo.LoginUser;
import org.jeecg.common.util.oConvertUtils;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import lombok.extern.slf4j.Slf4j;

import org.jeecg.modules.entity.Notice;
import org.jeecg.modules.service.INoticeService;
import org.jeecg.modules.vo.VoNotice;
import org.jeecgframework.poi.excel.ExcelImportUtil;
import org.jeecgframework.poi.excel.def.NormalExcelConstants;
import org.jeecgframework.poi.excel.entity.ExportParams;
import org.jeecgframework.poi.excel.entity.ImportParams;
import org.jeecgframework.poi.excel.view.JeecgEntityExcelView;
import org.jeecg.common.system.base.controller.JeecgController;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.multipart.MultipartHttpServletRequest;
import org.springframework.web.servlet.ModelAndView;
import com.alibaba.fastjson.JSON;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.jeecg.common.aspect.annotation.AutoLog;

 /**
 * @Description: 公告表
 * @Author: jeecg-boot
 * @Date:   2020-09-12
 * @Version: V1.0
 */
@Api(tags="公告表")
@RestController
@RequestMapping("/org/notice")
@Slf4j
public class NoticeController extends JeecgController<Notice, INoticeService> {
	@Autowired
	private INoticeService noticeService;

	/**
	 * 分页列表查询
	 *
	 * @param notice
	 * @param pageNo
	 * @param pageSize
	 * @param req
	 * @return
	 */
	@AutoLog(value = "公告表-分页列表查询")
	@ApiOperation(value="公告表-分页列表查询", notes="公告表-分页列表查询")
	@GetMapping(value = "/list")
	public Result<?> queryPageList(Notice notice,
								   @RequestParam(name="pageNo", defaultValue="1") Integer pageNo,
								   @RequestParam(name="pageSize", defaultValue="10") Integer pageSize,
								   HttpServletRequest req) {
		QueryWrapper<Notice> queryWrapper = QueryGenerator.initQueryWrapper(notice, req.getParameterMap());
//		queryWrapper.eq("notice_status",1);
		queryWrapper.orderByDesc("create_time");
		Page<Notice> page = new Page<Notice>(pageNo, pageSize);
		IPage<Notice> pageList = noticeService.page(page, queryWrapper);
		pageList.getRecords().forEach((res)->{
			if (res.getNoticeImg()!=null){
				res.setNoticeImg(FilePathConstant.PRE_FILEPATH_DOWNLOAD+res.getNoticeImg());
			}
		});
        return Result.ok(pageList);
    }

	/**
	 *   添加
	 *
	 * @param voNotice
	 * @return
	 */
	@AutoLog(value = "公告表-添加")
	@ApiOperation(value="公告表-添加", notes="公告表-添加")
	@PostMapping(value = "add")
	public Result<?> add(@RequestBody VoNotice voNotice) {
		Notice notice = voNotice.getNotice();
		// get loginUser and to set CreateBy
		log.info("进入公告添加=====>"+notice.toString());
		Subject subject = SecurityUtils.getSubject();
		LoginUser loginUser = (LoginUser) subject.getPrincipal();
		try {
			notice.setCreateBy(loginUser.getRealname());
		} catch (Exception e) {
			notice.setCreateBy("admin");
		}
		//to update filesPath
		String filesPath = voNotice.getFilesPath();
		if (filesPath!=null){
		    changePath(filesPath,notice);
        }
		noticeService.save(notice);
		return Result.ok("添加成功！");
	}

     /**
      * change Path for links
      * @param filesPath filePath
      * @param notice notice
      */
	private void changePath(String filesPath,Notice notice){
        // filesPath is not null
        String[] temps = filesPath.split(",");
        StringBuffer link = new StringBuffer();
        StringBuffer text = new StringBuffer(notice.getNoticeText());
        int i = 1;
        for (String temp : temps) {
            // constructe a tag
            link.append("<p><a href=\"");
            link.append(FilePathConstant.PRE_FILEPATH_DOWNLOAD+temp);
            String[] split = temp.split("/");
            String fileName = split[split.length-1];
            link.append("\">附件： "+fileName+"</a></p>");
            // text + link
            text.append(link);
            // clear link
            link.setLength(0);
            i++;
        }
        notice.setNoticeText(text.toString());
    }
	/**
	 *  编辑
	 *
	 * @param voNotice view layer form elements
	 * @return
	 */
	@AutoLog(value = "公告表-编辑")
	@ApiOperation(value="公告表-编辑", notes="公告表-编辑")
	@PutMapping(value = "edit")
	public Result<?> edit(@RequestBody VoNotice voNotice) {
		// get loginUser and update updateBy
		Subject subject = SecurityUtils.getSubject();
		LoginUser loginUser = (LoginUser) subject.getPrincipal();
		Notice notice = voNotice.getNotice();
        try {
            notice.setUpdateBy(loginUser.getRealname());
        } catch (Exception e) {
            notice.setUpdateBy("admin");
        }

        // check filesPath is null?
        String filesPath = voNotice.getFilesPath();
        if (filesPath!=null){
            // filesPath is not null
            changePath(filesPath,notice);
        }
        noticeService.updateById(notice);
		return Result.ok("编辑成功!");
	}

	/**
	 *   通过id删除
	 *
	 * @param id  notice's id
	 * @return
	 */
	@AutoLog(value = "公告表-通过id删除")
	@ApiOperation(value="公告表-通过id删除", notes="公告表-通过id删除")
	@DeleteMapping(value = "delete")
	public Result<?> delete(@RequestParam(name="id",required=true) String id) {
		noticeService.removeById(id);
		return Result.ok("删除成功!");
	}

	/**
	 *  批量删除
	 *
	 * @param ids  array notice's id
	 * @return
	 */
	@AutoLog(value = "公告表-批量删除")
	@ApiOperation(value="公告表-批量删除", notes="公告表-批量删除")
	@DeleteMapping(value = "deleteBatch")
	public Result<?> deleteBatch(@RequestParam(name="ids",required=true) String ids) {
		this.noticeService.removeByIds(Arrays.asList(ids.split(",")));
		return Result.ok("批量删除成功!");
	}

	/**
	 * 通过id查询
	 *
	 * @param id
	 * @return
	 */
	@AutoLog(value = "公告表-通过id查询")
	@ApiOperation(value="公告表-通过id查询", notes="公告表-通过id查询")
	@GetMapping(value = "queryById")
	public Result<?> queryById(@RequestParam(name="id",required=true) String id) {
		Notice notice = noticeService.getById(id);
		if(notice==null) {
			return Result.error("未找到对应数据");
		}
		return Result.ok(notice);
	}

    /**
    * 导出excel
    *
    * @param request
    * @param notice
    */
    @RequestMapping(value = "exportXls")
    public ModelAndView exportXls(HttpServletRequest request, Notice notice) {
        return super.exportXls(request, notice, Notice.class, "公告表");
    }

    /**
      * 通过excel导入数据
    *
    * @param request
    * @param response
    * @return
    */
    @RequestMapping(value = "importExcel", method = RequestMethod.POST)
    public Result<?> importExcel(HttpServletRequest request, HttpServletResponse response) {
        return super.importExcel(request, response, Notice.class);
    }

}
